import base64
import json
import math
import time
import uuid
import random
import sys
sys.path.append("/java_web/cloudcs2mon/pyspace/")
import os
os.chdir(os.path.dirname(__file__))
print("1",os.path.dirname(__file__))

import logs
import confhelper
import requests
import subprocess
from playwright.sync_api import Playwright, sync_playwright

import dbmapper
from entity import LinkMonResult, MonLinkBatch, MonLinkVersion, MonLink

logger = logs.get_logger('jd')

wiew_size = {"width": 1080, "height": 2240}
linkpath_prefix = confhelper.confdata().get("linkpath_prefix")+"jd/"
work_dir = confhelper.confdata().get("work_dir")
urls = []
monLinks = []
page_size = 60
picList = []

logger.info("sys.argv: {}".format(sys.argv))
version = sys.argv[1]

#输入Chrome浏览器所在路径
chrome_path = r'"C:\Program Files\Google\Chrome\Application\chrome.exe"'
debugging_port = "--remote-debugging-port=9222"
command = f"{chrome_path} {debugging_port}"
subprocess.Popen(command, shell=True)

def run(playwright: Playwright) -> None:
    # browser = playwright.firefox.launch(headless=False,slow_mo=3000)
    # context = browser.new_context(screen=wiew_size,viewport=wiew_size,storage_state="jd_state.json")
    # page = context.new_page()

    browser = playwright.chromium.connect_over_cdp("http://localhost:9222", slow_mo=3000)
    context = browser.contexts[0]
    page = context.pages[0]

    i = 0
    processI = 0
    for link in monLinks:
        processI = processI + 1
        logger.info("爬取进度：{}/{}".format(processI, len(monLinks)))

        url = link.url
        linkId = link.id
        logger.info("开始遍历 url:{} id:{}".format(url,linkId))
        page.goto(url)
        if page.locator("text=搜本店").count() == 0:
            logger.error("无效店铺: {}".format(url))
            dbmapper.MonLinkMapper.updateInvalid(MonLink(id=linkId))
            continue
        if page.locator(".J_giftClose.d-close").count()>0:
            logger.info("出现领券框")
            page.locator(".J_giftClose.d-close").click()
        page.locator("text=搜本店").click()
        #with page.expect_navigation():
        pageTotal = page.locator(".jSearchListArea").locator(".jTotal>em").text_content()
        pageNum = math.ceil(int(pageTotal)/page_size)
        logger.info("url {} pageTotal {} pagenum: {} ".format(url,pageTotal,pageNum))

        monLinkBatch=MonLinkBatch(linkId=linkId)
        linkBatchCount = dbmapper.MonLinkBatchMapper.count(monLinkBatch)
        if int(linkBatchCount) > 0:
            dbmapper.MonLinkBatchMapper.update(MonLinkBatch(goodSum=pageTotal,linkId=linkId))
        else:
            monLinkBatchInsert=MonLinkBatch(goodSum=pageTotal,linkId=linkId,status='0',linkUrl=url)
            dbmapper.MonLinkBatchMapper.insert(monLinkBatchInsert)
        for p_num in range(1,pageNum+1):
            #page.reload();
            logger.info("当前网站进度：{}/{},url :{} linkId :{}".format(p_num, pageNum, url, linkId))
            if(p_num > 1):
                page.locator("text=下一页").click()
            #print("第"+str(p_num)+"页 url size: "+str(len(pageLinks)))
            pageLinks = page.locator(".jSearchListArea").locator(".jSubObject").all()
            if len(pageLinks) > 0 :
                view_page(p_num,i,page,pageLinks,picList,url,linkId)
        logger.info("结束遍历 {}".format(url))

        monLinkUpdate=MonLink(version=version, id=linkId)
        dbmapper.MonLinkMapper.update(monLinkUpdate)
    # Close page
    page.close()
    # ---------------------
    context.close()
    browser.close()

def view_page(p_num:int,i:int,page,pageLinks,picList,linkUrl,linkId):
    for p in pageLinks:
        i = i + 1
        j = 0
        logger.info("每项进度：{}/{},linkId:{}".format(i, len(pageLinks), linkId))
        try:
            with page.expect_popup(timeout=60000) as popup_info:
                p.click()
                time.sleep(0.5)
            page1 = popup_info.value
            time.sleep(0.5)
            page1.wait_for_timeout(1000)

            while page1.locator("text=验证").count() >0:
                logger.info("出现图形验证等待5秒")
                #time.sleep(5)
                page1.wait_for_timeout(5000)
            if page1.locator("text=商品介绍").count() > 0 :
                if page1.locator("text=验证").count() == 0:
                    pic = linkpath_prefix +str(p_num)+"-"+str(i)+"-"+str(j)+page1.title().replace("*","").replace("/","#").replace(" ","")[0:30]+".png"
                    page1.wait_for_timeout(3000)
                    page1.wait_for_load_state('networkidle')
                    page1.screenshot(path=pic,full_page=True)
                    picList.append(pic)
                    linkMonResult = LinkMonResult(str(uuid.uuid4().int),linkUrl,page1.url,"/profile"+pic.replace(work_dir,""),linkId=linkId)
                    count = dbmapper.LinkMonResultMapper.count(linkMonResult)
                    if int(count) > 0:
                        linkMonResult.status=0
                        linkMonResult.ocrStr=""
                        dbmapper.LinkMonResultMapper.update(linkMonResult)
                    else:
                        dbmapper.LinkMonResultMapper.insert(linkMonResult)

                    linkVersion=MonLinkVersion(linkId=linkId, linkUrl=linkUrl, goodUrl=page1.url,version=version)
                    lvCount = dbmapper.MonLinkVersionMapper.count(linkVersion);
                    if int(lvCount) <= 0:
                        dbmapper.MonLinkVersionMapper.insert(linkVersion)
                else:
                    logger.info("出现图形验证进入60秒睡眠")
                    #time.sleep(60)
                    page1.wait_for_timeout(60000)
            page1.close()
        except Exception as e:
            logger.info("exception {} url:{}".format(i,page1.url))
            logger.exception("exception traceback is:{}".format(e))
            page1.close()
            #pageList.append(popup_info.value)

os.chdir(os.path.dirname(__file__))
# 通过db加载url
monLink = dbmapper.MonLinkMapper.list_by_typea('jd', version)
if len(monLink) > 0:
    monLinks = monLink

logger.info("待监测的url %s",[(link.id,link.url) for link in monLinks])
if len(monLinks) > 0:
    with sync_playwright() as playwright:
        run(playwright)
